package com.zjm.zdk.nio;

import java.nio.ByteBuffer;

public class DirectBufferDemo {
    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocateDirect(4);
        System.out.println(String.format("初始化：capacity容量：%d, position位置：%d, limit限制：%d",
                buffer.capacity(), buffer.position(), buffer.limit()));
        buffer.put((byte)1);
        buffer.put((byte)2);
        buffer.put((byte)3);
        System.out.println(String.format("写入3字节后：capacity容量：%d, position位置：%d, limit限制：%d",
                buffer.capacity(), buffer.position(), buffer.limit()));
        buffer.flip();
        System.out.println(String.format("转化为读取模式：capacity容量：%d, position位置：%d, limit限制：%d",
                buffer.capacity(), buffer.position(), buffer.limit()));
        System.out.println("...读取数据");
        byte a = buffer.get();
        System.out.println(a);
        byte b = buffer.get();
        System.out.println(b);
        System.out.println(String.format("读取2字节后：capacity容量：%d, position位置：%d, limit限制：%d",
                buffer.capacity(), buffer.position(), buffer.limit()));
        buffer.compact();// 压缩：清楚已读，全部左移 《=
        buffer.put((byte)3);
        buffer.put((byte)4);
        buffer.put((byte)5);
        System.out.println(String.format("最终的情况：capacity容量：%d, position位置：%d, limit限制：%d",
                buffer.capacity(), buffer.position(), buffer.limit()));
    }
}
